package mytest.bb;

import java.util.Random;

import sde.actor.Actor;
import sde.actor.Message;

public class Consumer extends Actor {
	
	private static class Consume extends Message{}
	
	private static int ID=0;
	
	private final int id;
	
	private final byte CREATED = 0, WAITING = 1, CONSUMING = 2;//stati
	
	private BufferIF buffer;
	
	private Random random = new Random();
	
	public Consumer(){
		id=++ID;
		become(CREATED);
	}
	
	public void init(BufferIF buffer){
		this.buffer=buffer;
		buffer.send(new BufferIF.Get(this));
	}

	@Override
	public void handler(Message m) {
		switch(currentStatus()){
		case CREATED:
			if(m instanceof BufferIF.Get.Reply){
				int num = ((BufferIF.Get.Reply) m).getVal();
				System.out.println("Consumer#" + id + " got item#" + num + " @"
						+ now());
				become(CONSUMING);
				send(new Consume(), now() + random.nextDouble() * 100);
			}
			break;
		case WAITING:
			if(m instanceof BufferIF.Get.Reply){
				int num = ((BufferIF.Get.Reply) m).getVal();
				System.out.println("Consumer#" + id + " got item#" + num + " @"
						+ now());
				become(CONSUMING);
				send(new Consume(), now() + random.nextDouble() * 100);
			}
			break;
		case CONSUMING:
			if(m instanceof Consume){
				buffer.send(new BufferIF.Get(this));
				become(WAITING);
			}
			break;
		}
	}
}
